package leecode;

/**
 * @author csp 2021-04-26
 */
public class Question8 {
    public static void main(String[] args) {
        Question8 question8 = new Question8();
        final int i = question8.myAtoi("words and 987");
        System.out.println(i);
    }
    char[] nums = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};

    public int myAtoi(String s) {
        int index = 0;
        int end = 0;
        boolean start = false;
        for (int i = 0; i < s.length(); i++) {
            if (check(s.charAt(i))) {
                if (!start) {
                    index = i;
                    start = true;
                }
                if (i == s.length() - 1) {
                    end = i;
                }
            } else {
                if (start) {
                    end = i-1;
                    break;
                }
            }
        }
        if (end == index) {
            return 0;
        }
        String num = s.substring(index, end+1);
        int sum = tran(num);
        return sum;
    }

    private boolean check(char c) {
        for (char num : nums) {
            if (num == c) {
                return true;
            }
        }
        return false;
    }

    private int tran(String num) {
        int sum = 0;
        for (int i = 0; i < num.length(); i++) {
            final char c = num.charAt(i);
            int n = c - '0';
            int k = 1;
            for (int j = num.length() - 1 - i; j > 0; j--) {
                k *= 10;
            }
            sum += n * k;
        }
        return sum;
    }
}
